﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml;
using System.IO;

namespace doDesktop
{
    public partial class FormSMS : Form
    {
        #region PROPERTIES
        /// <summary>
        /// The information of user
        /// </summary>
        XmlNode _xmlNodeAccount = null;
        /// <summary>
        /// Groups list
        /// </summary>
        XmlNodeList _xmlNodeList = null;
        /// <summary>
        /// If use the phones textbox, the numbers is in this array
        /// </summary>
        string[] _numbers = new string[] { };
        /// <summary>
        /// Templates list loaded from API
        /// </summary>
        List<XmlDocument> _templates = new List<XmlDocument>();
        /// <summary>
        /// Number of SMS credits of user
        /// </summary>
        int _credits = 0;
        /// <summary>
        /// Sender Name
        /// </summary>
        string _sender = "";
        #endregion

        /// <summary>
        /// Get the xmlNodeAccount, where is the users information loaded in Login
        /// </summary>
        /// <param name="xmlNode"></param>
        public FormSMS(XmlNode xmlNode = null)
        {
            _xmlNodeAccount = xmlNode;
            InitializeComponent();
        }
        /// <summary>
        /// When the form load poppulate all
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormSMS_Load(object sender, EventArgs e)
        {
            this.Text = Resource_ES.Hello + ", " + _xmlNodeAccount.SelectSingleNode("accountname").InnerText;
            labelMessage.Text = "";
            dateTimePickerScheduled.MinDate = DateTime.Now;
            GetSender();
            UpdateCreadits();
            GetTemplates();
        }
        /// <summary>
        /// Update the characters counter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            int counter = ((TextBox)sender).Text.Length;

            labelCount.Text = counter + " " + Resource_ES.characters;


            int counterSms = Math.Abs(counter / 160) + 1;
            labelCount.Text += " " + counterSms + " " + Resource_ES.message;
        }
        /// <summary>
        /// Disable edit and go to the confirm for send the SMS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSend_Click(object sender, EventArgs e)
        {
            labelMessage.ForeColor = Color.FromArgb(218, 100, 90);

            if (textBoxSender.Text == "")
            {
                labelMessage.Text = Resource_ES.errorsender;
                return;
            }
            if (textBoxPhones.Text == "" && tabControlReceiver.SelectedTab == tabPagePhones)
            {
                labelMessage.Text = Resource_ES.errorphones;
                return;
            }
            if (checkedListBoxGroups.CheckedItems.Count < 1 && tabControlReceiver.SelectedTab == tabPageGroups)
            {
                labelMessage.Text = Resource_ES.errorgroups;
                return;
            }
            if (textBoxSMS.Text == "")
            {
                labelMessage.Text = Resource_ES.errormessage;
                return;
            }
            //Update the senderName
           
            if (_sender != textBoxSender.Text)
            {
                Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.InnerXml = mandoo.doSms_SetSender(textBoxSender.Text);
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/nodes/result");
                if (int.Parse(xmlNode.InnerText) != 1)
                {
                    labelMessage.Text = Resource_ES.errorupdatesender;
                    return;
                }
                _sender = textBoxSender.Text;
            }
            try
            {
                int counterSms = Math.Abs(textBoxSMS.Text.Length / 160) + 1;
                int credits = 0;

                if (tabControlReceiver.SelectedTab == tabPagePhones)
                {
                    textBoxPhones.Text = textBoxPhones.Text.Replace(" ", "");
                    _numbers = textBoxPhones.Text.Split(';');
                    _numbers = _numbers.Distinct().ToArray();
                    _numbers = _numbers.Where(x => !string.IsNullOrEmpty(x)).ToArray();

                    textBoxPhones.Text = string.Join(";", _numbers);

                    credits = _numbers.Length * counterSms;
                }
                else
                {
                    int groupnumbers = 0;
                    foreach (Group o in checkedListBoxGroups.CheckedItems)
                    {
                        groupnumbers += o.Suscriptors;
                    }
                    credits = groupnumbers * counterSms;
                }
                if (_credits < credits)
                {
                    labelMessage.Text = Resource_ES.insufficientcredits;
                    return;
                }

                buttonSend.Visible = false;
                panelConfirm.Visible = true;
                textBoxPhones.ReadOnly = true;
                textBoxSender.ReadOnly = true;
                textBoxSMS.ReadOnly = true;
                dateTimePickerScheduled.Enabled = false;
                buttonImport.Enabled = false;
                labelMessage.Text = "";
                labelTotal.Text = "";
                tabControlReceiver.Enabled = false;
                labelTotal.Text = credits + " " + Resource_ES.ApproximateCreditCost;
                buttonAdd.Enabled = false;
            }
            catch
            {
                labelMessage.Text = Resource_ES.erroranerror;
            }
        }
        /// <summary>
        /// Get the SMS templates from API
        /// </summary>
        private void GetTemplates() 
        {
            Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.InnerXml = mandoo.doSms_GetTemplates(-1);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("/nodes/result");
            int selected = comboBoxTemplates.Items.Add(new Template("Ninguna", 0));
            foreach (XmlNode xmlNodeTemplate in xmlNode.ChildNodes)
            {
                int id = int.Parse(xmlNodeTemplate.SelectSingleNode("id").InnerText);
                int enabled = int.Parse(xmlNodeTemplate.SelectSingleNode("enabled").InnerText);
                string subject = xmlNodeTemplate.SelectSingleNode("newslettertemplates_subject").InnerText;

                comboBoxTemplates.Items.Add(new Template(subject, id));
            }
            comboBoxTemplates.SelectedIndex = selected;
        }
        /// <summary>
        /// Get the default sender
        /// </summary>
        private void GetSender()
        {
            Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.InnerXml = mandoo.doSms_GetSender();
            XmlNode xmlNode = xmlDocument.SelectSingleNode("/nodes/result");
            string senderName = xmlNode.SelectSingleNode("paName").InnerText;
            if (senderName == null || senderName == "")
            {
                textBoxSender.Text = _xmlNodeAccount.SelectSingleNode("accountname").InnerText.Substring(0, 11);
            }
            else 
            { 
                textBoxSender.Text = senderName;
                _sender = senderName;
            }
        }
        /// <summary>
        /// Cancel the SMS and return to edit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCancelSend_Click(object sender, EventArgs e)
        {
            panelConfirm.Visible = false;
            buttonSend.Visible = true;
            textBoxPhones.ReadOnly = false;
            textBoxSender.ReadOnly = false;
            textBoxSMS.ReadOnly = false;
            dateTimePickerScheduled.Enabled = true;
            buttonImport.Enabled = true;
            tabControlReceiver.Enabled = true;
            buttonAdd.Enabled = true;
        }
        /// <summary>
        /// Send the SMS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSendConfirmed_Click(object sender, EventArgs e)
        {
            buttonSendConfirmed.Enabled = false;
            Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
            XmlDocument xmlDocument = new XmlDocument();

            if (tabControlReceiver.SelectedTab == tabPagePhones)
            {
                xmlDocument.InnerXml = mandoo.doSms_SendSMS_Phones(0, _numbers, textBoxSMS.Text, "doDesktop " + DateTime.Now, dateTimePickerScheduled.Value);
            }
            else 
            {
                List<string> values = new List<string>();
                foreach (Group o in checkedListBoxGroups.CheckedItems)
                {
                    values.Add(o.Value.ToString());
                }
                string groups = String.Join(",", values.ToArray());
                xmlDocument.InnerXml = mandoo.doSms_SendSMS(0, groups, textBoxSMS.Text, "doDesktop " + DateTime.Now, dateTimePickerScheduled.Value);
            }
            XmlNode xmlNode = xmlDocument.SelectSingleNode("/nodes");
            try
            {
                int id = int.Parse(xmlNode.SelectSingleNode("result").InnerText);
                if (id > 0)
                {
                    if (DateTime.Now > dateTimePickerScheduled.Value)
                    {
                        UpdateCreadits();
                    }
                    buttonSendConfirmed.Enabled = true;
                    labelMessage.ForeColor = Color.FromArgb(39, 174, 96);
                    labelMessage.Text = Resource_ES.sendedmessage;
                }
                else 
                {
                    labelMessage.ForeColor = Color.FromArgb(218, 100, 90);
                    labelMessage.Text = Resource_ES.errornosendsms;
                }
            }
            catch 
            {
                labelMessage.ForeColor = Color.FromArgb(218, 100, 90);
                labelMessage.Text = Resource_ES.errornosendsms;
            }
            buttonCancelSend_Click(sender, e);
        }
        /// <summary>
        /// Update the user SMS credits
        /// </summary>
        private void UpdateCreadits()
        {
            Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.InnerXml = mandoo.doSms_GetCredits();
            XmlNode xmlNode = xmlDocument.SelectSingleNode("/nodes/result/node");
            _credits = int.Parse(xmlNode.SelectSingleNode("credits").InnerText);
            labelCredits.Text = _credits + " " + Resource_ES.credits;
        }
        /// <summary>
        /// Start new Browser if user click on buy link
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabelBuy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(Resource_ES.mandooproductsurl);
        }
        /// <summary>
        /// Not import, now only read a file a put on textboxphones
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonImport_Click(object sender, EventArgs e)
        {
            labelMessage.Text = "";
            labelMessage.ForeColor = Color.FromArgb(218, 100, 90);
            DialogResult dialogResult = openFileDialogImport.ShowDialog();
            if (dialogResult == DialogResult.OK) // Test result.
            {
                try
                {
                    string file = openFileDialogImport.FileName;
                    string ext = Path.GetExtension(file).ToLower();

                    switch (ext)
                    {
                        case ".txt":
                        case ".csv":
                            textBoxPhones.Text = File.ReadAllText(file);
                            break;
                        default:
                            labelMessage.Text = Resource_ES.filenotsupported;
                            break;
                    }
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// Change the receiver tabs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControlReceiver_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlReceiver.SelectedTab == tabPagePhones)
            {
                buttonImport.Visible = true;
            }
            else 
            {
                buttonImport.Visible = false;
            }
            if (_xmlNodeList == null)
            {
                Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);

                XmlDocument xmlDocumentGroups = new XmlDocument();
                xmlDocumentGroups.InnerXml = mandoo.doSms_Groups(null);
                XmlNode xmlNode = xmlDocumentGroups.SelectSingleNode("/nodes");

                _xmlNodeList = xmlNode.ChildNodes;
                foreach (XmlNode xmlNodeGroup in _xmlNodeList)
                {

                    int enabled = int.Parse(xmlNodeGroup.SelectSingleNode("enabled").InnerText);
                    int numsmssubscribers = int.Parse(xmlNodeGroup.SelectSingleNode("numsmssubscribers").InnerText);

                    if (enabled == 1 && numsmssubscribers > 0)
                    {
                        string title = xmlNodeGroup.SelectSingleNode("title").InnerText + " (" + numsmssubscribers + ")";

                        Group group = new Group(title, int.Parse(xmlNodeGroup.SelectSingleNode("id").InnerText), numsmssubscribers);
                        checkedListBoxGroups.Items.Add(group);
                        
                    }
                }
            }
        }
        /// <summary>
        /// Load Template and put on cache List, if the template is on cache, load from cache directly
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSelectTemplate_Click(object sender, EventArgs e)
        {

            Template template = (Template)comboBoxTemplates.SelectedItem;
            if (template.Value == 0)
            {
                textBoxSMS.Text = "";
            }
            else 
            {
                XmlDocument xmlDocumentTemplates = new XmlDocument();
                XmlDocument _tpl = null;
                if (_templates.Count > 0)
                {
                    _tpl = _templates.Find(r => int.Parse(r.SelectSingleNode("/nodes/result/node/id").InnerText) == template.Value);
                }

                if (_tpl == null)
                {
                    Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
                    xmlDocumentTemplates.InnerXml = mandoo.doSms_GetTemplate(template.Value);
                    _templates.Add(xmlDocumentTemplates);
                   
                }
                else 
                {
                    xmlDocumentTemplates = _tpl;
                }
                try
                {
                    XmlNode xmlNode = xmlDocumentTemplates.SelectSingleNode("/nodes/result/node/newslettertemplates_body");
                    textBoxSMS.Text += xmlNode.InnerText;
                }
                catch 
                {
                    textBoxSMS.Text += "";
                }
            }
        }
        /// <summary>
        /// Add date to SMS message
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            textBoxSMS.Text += dateTimePickerDate.Value.ToString("dd/MM/yyyy HH:mm");
            
        }
        /// <summary>
        /// Save the SMS as template
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSaveTemplate_Click(object sender, EventArgs e)
        {
            labelMessage.Text = "";
            Mandoo.DoAPI mandoo = new Mandoo.DoAPI(_xmlNodeAccount.SelectSingleNode("client_id").InnerText, _xmlNodeAccount.SelectSingleNode("client_secret").InnerText);
            XmlDocument xmlDocument = new XmlDocument();
            string subject = textBoxSMS.Text;
            if (subject.Length == 0) 
            {
                labelMessage.Text = Resource_ES.errormessage;
                return;
            }
            if (subject.Length > 50)
            {
                subject = subject.Substring(0, 50);
            }
            xmlDocument.InnerXml = mandoo.doSms_SaveAsTemplate(0, subject, textBoxSMS.Text);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("/nodes/result");
            if (xmlNode != null && int.Parse(xmlNode.InnerText) > 0)
            {
                comboBoxTemplates.Items.Add(new Template(subject, int.Parse(xmlNode.InnerText)));
                labelMessage.ForeColor = Color.FromArgb(39, 174, 96);
                labelMessage.Text = Resource_ES.savetemplateok;
            }
            else
            {
                labelMessage.ForeColor = Color.FromArgb(218, 100, 90);
                labelMessage.Text = Resource_ES.errorsavetemplate;
            }
        }
        /// <summary>
        /// Put the sender text on the sms
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSender_Click(object sender, EventArgs e)
        {
            textBoxSMS.Text += textBoxSender.Text;
        }
    }
}
